package com.example.demo.controller.train;
import java.util.ArrayList;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.constants.SubmissionSourceModuleConstant;
import com.example.demo.domain.entity.TrainCommitRecord;
import com.example.demo.domain.entity.TrainHomework;
import com.example.demo.domain.entity.VojSubmissions;
import com.example.demo.domain.model.UserTrainCommitRecordForm;
import com.example.demo.dto.ResponseDto;
import com.example.demo.enums.TrainEvalStatusEnum;
import com.example.demo.param.voj.SubmissionCreateParam;
import com.example.demo.service.TrainCommitRecordService;
import com.example.demo.service.TrainHomeworkService;
import com.example.demo.service.VojSubmissionsService;
import com.example.demo.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.tomcat.jni.Time;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户-代码提交暂存相关
 * @author liguang03
 * @date 2024/2/4
 */
@Controller
@Slf4j
@RequestMapping("/train/train-user-commit")
public class TrainCommitRecordController {


    @Resource
    private TrainCommitRecordService trainCommitRecordService;


    @Resource
    private VojSubmissionsService vojSubmissionsService;


    @Resource
    private TrainHomeworkService trainHomeworkService;


    /**
     * 获取用户某个班级作业题目的所有提交记录
     * @param homeworkId
     * @param problemId
     * @param classId
     * @return
     */
    @RequestMapping("/record")
    @ResponseBody
    public ResponseDto getCommitRecord(Long homeworkId, Long problemId, Long classId){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null){
            return new ResponseDto().buildFail("禁止操作");
        }
        List<TrainCommitRecord> trainCommitRecords =
                trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(homeworkId, problemId, classId, userInfo.getUser().getId());
        if (CollectionUtils.isEmpty(trainCommitRecords)){
            return new ResponseDto().buildSucceed();
        }
        //去除暂存的，一般是没有提交时间或者SubmitId的
        List<TrainCommitRecord> collect = trainCommitRecords.stream().filter(trainCommitRecord -> !CommonUtil.isNullId(trainCommitRecord.getSubmitId()))
                .collect(Collectors.toList());
        return new ResponseDto().buildSucceedHasData(collect);
    }


    /**
     * 代码信息临时保存
     * @param form
     * @return
     */
    @RequestMapping("/tmp-save")
    @ResponseBody
    public ResponseDto<TrainCommitRecord> saveTmpCommitRecord(UserTrainCommitRecordForm form){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null){
            return new ResponseDto().buildFail("禁止操作");
        }
        TrainHomework homework = trainHomeworkService.getById(form.getHomeworkId());
        if (homework == null) {
            return new ResponseDto<>().buildFail("作业不存在");
        }
        Date endTime = homework.getEndTime();
        Date date = new Date();
        if (date.after(endTime)){
            return new ResponseDto<>().buildFail("作业已结束，禁止保存");
        }

        TrainCommitRecord trainCommitRecord = new TrainCommitRecord();
        trainCommitRecord.setId(form.getId());
        trainCommitRecord.setClassId(form.getClassId());
        trainCommitRecord.setUsername(userInfo.getUser().getUsername());
        trainCommitRecord.setProblemId(form.getProblemId());
        trainCommitRecord.setLanguage(form.getLanguage());
        trainCommitRecord.setAnswer(form.getAnswer());
        trainCommitRecord.setUserId(userInfo.getUser().getId());
        trainCommitRecord.setHomeworkId(form.getHomeworkId());
        if (CommonUtil.isNullId(form.getId())){
            trainCommitRecordService.save(trainCommitRecord);
        }else {
            trainCommitRecordService.updateById(trainCommitRecord);
        }
        return new ResponseDto().buildSucceedHasData(trainCommitRecord);
    }




    /**
     * 获取临时存储的代码信息，没有则为空
     * @param form
     * @return
     */
    @RequestMapping("/get-tmp-save")
    @ResponseBody
    public ResponseDto<TrainCommitRecord> getTmpCommitRecord(UserTrainCommitRecordForm form){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null){
            return new ResponseDto().buildFail("禁止操作");
        }

        Long homeworkId = form.getHomeworkId();
        Long problemId = form.getProblemId();
        Long classId = form.getClassId();
        List<TrainCommitRecord> trainCommitRecords =
                trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(homeworkId, problemId, classId, userInfo.getUser().getId());
        if (CollectionUtils.isEmpty(trainCommitRecords)){
            return new ResponseDto().buildSucceed();
        }
        //去除暂存的，一般是没有提交时间或者SubmitId的
        TrainCommitRecord trainCommitRecord = trainCommitRecords.stream()
                .filter(tmp -> CommonUtil.isNullId(tmp.getSubmitId()))
                .min((t1, t2) -> t2.getUpdateTime().compareTo(t1.getUpdateTime()))
                .orElse(null);

        return new ResponseDto().buildSucceedHasData(trainCommitRecord);
    }

    /**
     * 提交代码
     * @param form
     * @return
     */
    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto<TrainCommitRecord> submit(@RequestBody UserTrainCommitRecordForm form){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null){
            return new ResponseDto().buildFail("禁止操作");
        }
        if (StringUtils.isBlank(form.getLanguage()) || !NumberUtils.isCreatable(form.getLanguage())){
            return new ResponseDto<>().buildFail("请选择一门语言");
        }
        TrainHomework homework = trainHomeworkService.getById(form.getHomeworkId());
        if (homework == null) {
            return new ResponseDto<>().buildFail("作业不存在");
        }
        //判断提交次数及语言
        List<String> supportLanguage =
                new ArrayList<>(CommonUtil.collectionConvertor(homework.getLanguage(), s -> s));
        if (!supportLanguage.contains(form.getLanguage())){
            return new ResponseDto<>().buildFail("不支持的语言类型");
        }
        List<TrainCommitRecord> trainCommitRecords =
                trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(form.getHomeworkId(), form.getProblemId(),
                        form.getClassId(), userInfo.getUser().getId());
        if (CollectionUtils.isNotEmpty(trainCommitRecords)){
            List<TrainCommitRecord> collect = trainCommitRecords.stream().filter(trainCommitRecord -> CommonUtil.isNotNullId(trainCommitRecord.getSubmitId())).collect(Collectors.toList());
            if (collect.size() >= homework.getCommitTimes()){
                return new ResponseDto<>().buildFail("提交超过次数限制");
            }
        }
        Date endTime = homework.getEndTime();
        Date date = new Date();
        if (date.after(endTime)){
            return new ResponseDto<>().buildFail("作业已结束，禁止保存");
        }

        TrainCommitRecord trainCommitRecord = new TrainCommitRecord();
        trainCommitRecord.setId(form.getId());
        trainCommitRecord.setClassId(form.getClassId());
        trainCommitRecord.setUsername(userInfo.getUser().getUsername());
        trainCommitRecord.setProblemId(form.getProblemId());
        trainCommitRecord.setLanguage(form.getLanguage());
        trainCommitRecord.setAnswer(form.getAnswer());
        trainCommitRecord.setUserId(userInfo.getUser().getId());
        trainCommitRecord.setHomeworkId(form.getHomeworkId());
        trainCommitRecord.setSubmitTime(new Date());
        trainCommitRecord.setEvalStatus(TrainEvalStatusEnum.NOT_EVAL.getKey());
        //提交代码至评测机
        SubmissionCreateParam param = new SubmissionCreateParam();
        param.setProblemId(form.getProblemId());
        //languagId映射
        param.setLanguageId(Integer.parseInt(form.getLanguage()));
        param.setCode(form.getAnswer());
        param.setSourceModule(SubmissionSourceModuleConstant.TRAIN);
        Long submissionId = vojSubmissionsService.createSubmission(param);
        trainCommitRecord.setSubmitId(submissionId);
//        Time.sleep(3000);
        trainCommitRecord.setScore(vojSubmissionsService.getOne(new LambdaQueryWrapper<VojSubmissions>().eq(VojSubmissions::getSubmissionId, submissionId)).getSubmissionJudgeScore());
        if (CommonUtil.isNullId(form.getId())){
            trainCommitRecordService.save(trainCommitRecord);
        }else {
            trainCommitRecordService.updateById(trainCommitRecord);
        }
        return new ResponseDto().buildSucceedHasData(trainCommitRecord);
    }


    /**
     * 查询评测状态及结果 -给前端轮询查询评测状态使用
     * @param submitId
     * @return
     */
    @RequestMapping(value = "/get-submit-result",method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto<TrainCommitRecord> getSubmitStatus(Long submitId){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null){
            return new ResponseDto().buildFail("禁止操作");
        }
        TrainCommitRecord record = trainCommitRecordService.getBySubmissionId(submitId);
        return new ResponseDto().buildSucceedHasData(record);
    }















}
